package com.lanhai.longheng.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.lanhai.longheng.beans.DotBean;
import com.lanhai.longheng.dao.DotDao;
import com.lanhai.longheng.dao.QRAllowLeaveDao; 
import com.lanhai.longheng.enums.DotTypeEnum;
import com.lanhai.longheng.interfaces.IDot;
import com.lanhai.longheng.mapper.DotMapper;


@Service 
public class DotImpl implements IDot{
	 
	@Autowired
	DotMapper dotMapper;
	
	static List<DotDao> list=Collections.synchronizedList(new ArrayList<DotDao>());
	
	static Map<Integer,QRAllowLeaveDao> allowMap=Collections.synchronizedMap(new HashMap<Integer,QRAllowLeaveDao>());
	
	/**
	 *获取点位
	 */
	@Override
	public synchronized DotBean getBean(int dotno) { 
		if(list==null||list.size()==0) {
			if(list==null) {
				list=new ArrayList<DotDao>();
			}
			List<DotDao> tmp=dotMapper.getList();
			if(tmp!=null&&tmp.size()>0) {
				list.addAll(tmp);
			}
		}
		
		DotBean bean=null;
		for( DotDao dao:list) {
			if(dao.getDotno()==dotno) {
				bean=new DotBean();
				bean.setArea(dao.getX() , dao.getY(), dao.getRadius());
				bean.setDotName(dao.getDotname());
				bean.setDotNO(dotno);
				bean.setDotType(DotTypeEnum.getDotTypeEnum(dao.getPtype()));
				bean.setRouteRoad(dao.getRouteroad());  
				bean.setNextProcess(dao.getNextProcess());
			}
		}
		return bean; 
	}

	/**
	 *  
	 */
	@Override
	public synchronized DotBean getBeanByXY(int x, int y) { 
		if(list==null||list.size()==0) {
			if(list==null) {
				list=new ArrayList<DotDao>();
			}
			List<DotDao> tmp=dotMapper.getList();
			if(tmp!=null&&tmp.size()>0) {
				list.addAll(tmp);
			}
		}
		
		 
		DotBean bean=null;
		for( DotDao dao:list) {
			if(Math.abs(dao.getX()-x)<=dao.getRadius() && Math.abs(dao.getY()-y)<=dao.getRadius() ) {
				bean=new DotBean();
				bean.setArea(dao.getX() , dao.getY(), dao.getRadius());
				bean.setDotName(dao.getDotname());
				bean.setDotNO(dao.getDotno());
				bean.setDotType(DotTypeEnum.getDotTypeEnum(dao.getPtype()));
				bean.setRouteRoad(dao.getRouteroad());  
				bean.setNextProcess(dao.getNextProcess());
			}
		} 
		return bean;
	}

	   

	@Override
	public int getTransDotNo(int qrdotno) {
		Integer m=dotMapper.getTransDotNo(qrdotno);
		if(m==null) return 0;
		else return m; 
	}

	@Override
	public void clearDot() {
		list.clear();
	}

	 
	@Override
	public synchronized QRAllowLeaveDao getAllowLeave(int dotno) {
			QRAllowLeaveDao bean=allowMap.get(dotno);
			if(bean==null) {
				bean=dotMapper.getAllowLeave(dotno);
				if(bean!=null) {
					allowMap.put(dotno, bean);
				}
			}
		 return bean;
	}

}
